package com.ungs.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import com.ungs.form.HibernateConfig;
import com.ungs.readXML.ReadXMLFile;

/**
 * 
 * @author Joan Jimenez
 * @version 1.0
 */
public class ConexionBD {
	
	
	private String bd ;
	private String login ;
	private String password ;
	private String url ;

	Connection connection = null;

	public ConexionBD() {
		this.cargarDatosBD();
	}

	public Connection getConnection() {
		try {
	
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(url, login, password);
			if (connection != null) {
				System.out.println("Conexion a base de datos" + bd + " OK");
			}

		} catch (SQLException e1) {
			System.err.println(e1);
			JOptionPane.showMessageDialog(null,
					"Error al conectar a la base de datos.", "Error",
					JOptionPane.ERROR_MESSAGE);
			HibernateConfig config=new HibernateConfig();
			config.setVisible(true);
		} catch (ClassNotFoundException e2) {
			System.err.println(e2);
		}
		return connection;
	}

	public void desconectar() {
		connection = null;
		System.out.println("DESCONECTADO a base de datos");
	}


	private void cargarDatosBD(){
		ReadXMLFile file=new ReadXMLFile();
		this.bd=file.getEsquema();
		this.login=file.getUser();
		this.password=file.getPass();
		this.url="jdbc:mysql://"+file.getHost()+"/"+this.bd;
	}
}
